package com.daquexian.flexiblerichtextview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Base64Util {
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = bitmapToBase64(bitmap, MyConfige.base64_w_scale, MyConfige.base64_h_scale);
        return result;
    }

    public static String bitmapToBase64(Bitmap bitmap, float scale_w, float scale_h) {
        bitmap = bitmapZoom(bitmap, scale_w, scale_h);
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(result != null) {
            result = "data:image/png;base64," + result;
        }
        return result;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        //byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        String[] s_a = base64Data.split(",");
        if(s_a != null && s_a.length > 1) {
            byte[] bytes = Base64.decode(s_a[1], Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
        return null;
    }

    //bitmap 放大倍数
    public static Bitmap bitmapZoom(Bitmap bitmap, float f_w, float f_h) {
        if(bitmap != null && bitmap.getWidth() > 0 && bitmap.getHeight() > 0) {
            Matrix matrix = new Matrix();
            matrix.postScale(f_w, f_h);  //长和宽放大缩小的比例
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }
}
